package com.star.security;

import com.star.exception.SystemException;
import com.star.util.DateTimeUtil;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * token操作工具类
 *
 * @author tanyapeng
 * @date 2021/3/7
 */
@Component
@Slf4j
public class TokenManager {

    /**
     * token有效时长
     */
    private long tokenEcpiration = 24*60*60*1000;

    /**
     * 编码秘钥
     */
    private String tokenSignKey = "123456";

    /**
     * 1 使用jwt根据用户名生成token
     *
     * @param username
     * @return
     */
    public String createToken(String username) {
        try {
            String token = Jwts.builder()
                    .setSubject(username)
                    .setExpiration(new Date(LocalDateTime.now(DateTimeUtil.ZONE).toInstant(DateTimeUtil.OFFSET).toEpochMilli() + tokenEcpiration))
                    .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
            return token;
        } catch (Exception e) {
            log.error("createToken error - {},{},{}", ExceptionUtils.getStackTrace(e), username);
            throw new SystemException(10002, "生成token出错");
        }
    }

    /**
     * 2 根据token字符串得到用户信息
     *
     * @param token
     * @return
     */
    public String getUserInfoFromToken(String token) {
        try {
            String userinfo = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
            return userinfo;
        } catch (Exception e) {
            log.error("getUserInfoFromToken error - {},{},{}", ExceptionUtils.getStackTrace(e), token);
            throw new SystemException(10002, "获取用户信息出错");
        }
    }

    /**
     * 3 删除token
     *
     * @param token
     */
    public void removeToken(String token) { }

    public static void main(String[] args) {
        TokenManager tokenManager = new TokenManager();
        String typ = tokenManager.createToken("typ");
        System.out.println(typ);
    }
}
